package com.example.research.controller;

import com.example.research.dto.ApiResponse;
import com.example.research.entity.User;
import com.example.research.service.UserService;
import com.example.research.utils.PermissionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/user-management")
public class UserManagementController {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionUtils permissionUtils;

    /**
     * 管理员添加教师
     */
    @PostMapping("/teachers")
    public ApiResponse<User> addTeacher(@Valid @RequestBody User teacher,
                                       @RequestHeader("Authorization") String authHeader) {
        try {
            String token = authHeader.substring(7);

            // 验证当前用户是管理员
            if (!permissionUtils.isAdmin(token)) {
                return ApiResponse.forbidden("只有管理员可以添加教师");
            }

            User created = userService.createUser(teacher, "TEACHER");
            return ApiResponse.success("教师添加成功", created);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 教师添加学生
     */
    @PostMapping("/students")
    public ApiResponse<User> addStudent(@Valid @RequestBody User student,
                                       @RequestHeader("Authorization") String authHeader) {
        try {
            String token = authHeader.substring(7);

            // 验证当前用户是教师
            if (!permissionUtils.isTeacher(token)) {
                return ApiResponse.forbidden("只有教师可以添加学生");
            }

            // 设置学生的指导教师为当前用户
            Long currentUserId = permissionUtils.getCurrentUserId(token);
            student.setTeacherId(currentUserId.toString());

            User created = userService.createUser(student, "STUDENT");
            return ApiResponse.success("学生添加成功", created);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取教师负责的学生列表
     */
    @GetMapping("/teacher/{teacherId}/students")
    public ApiResponse<List<User>> getStudentsByTeacher(@PathVariable Long teacherId,
                                                       @RequestHeader("Authorization") String authHeader) {
        try {
            String token = authHeader.substring(7);
            Long currentUserId = permissionUtils.getCurrentUserId(token);

            // 验证权限：只能查看自己负责的学生或管理员可以查看所有
            if (!permissionUtils.isAdmin(token) && !currentUserId.equals(teacherId)) {
                return ApiResponse.forbidden("只能查看自己负责的学生");
            }

            List<User> students = userService.getStudentsByTeacher(teacherId);
            return ApiResponse.success(students);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 分配学生给教师
     */
    @PostMapping("/assign-student")
    public ApiResponse<String> assignStudentToTeacher(@RequestParam Long studentId,
                                                     @RequestParam Long teacherId,
                                                     @RequestHeader("Authorization") String authHeader) {
        try {
            String token = authHeader.substring(7);

            // 验证当前用户是管理员
            if (!permissionUtils.isAdmin(token)) {
                return ApiResponse.forbidden("只有管理员可以分配学生");
            }

            userService.assignStudentToTeacher(studentId, teacherId);
            return ApiResponse.success("学生分配成功");
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 用户更新个人详细信息
     */
    @PutMapping("/profile")
    public ApiResponse<User> updateProfile(@Valid @RequestBody User userInfo,
                                          @RequestHeader("Authorization") String authHeader) {
        try {
            String token = authHeader.substring(7);
            Long currentUserId = permissionUtils.getCurrentUserId(token);

            // 只能更新自己的信息
            userInfo.setId(currentUserId);
            User updated = userService.updateUser(userInfo);
            return ApiResponse.success("个人信息更新成功", updated);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
}
